﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GS.Cricket.Service.Impl.NHibernate;
using NHibernate;
using NHibernate.Criterion;

namespace GS.Cricket.Service.Impl
{
    public class PlayerService : IPlayerService
    {
        #region IPlayerService Members

        public int Add(Entities.Player player)
        {
            var existing = (Entities.Player)player.Name.GetByName<Entities.Player>();
            if (existing == null)
            {
                return (int)player.Add<Entities.Player>();
            }
            else
            {
                throw new NonUniqueObjectException("Player already exist", player, player.Name);
            }
        }

        public void Update(Entities.Player player)
        {
            player.Update<Entities.Player>();
        }

        public void Delete(int playerId)
        {
            var existing = (Entities.Player)playerId.GetById<Entities.Player>();
            if (existing != null)
            {
                existing.Delete<Entities.Player>();
            }
        }

        public Entities.Player GetById(int playerId)
        {
            return (Entities.Player)playerId.GetById<Entities.Player>();
        }

        public IEnumerable<Entities.Player> GetByTeam(int teamId)
        {
            using (ISession session = NHibernateHelper<Entities.Player>.OpenSession())
            {
                var result = session
                    .CreateCriteria(typeof(Entities.Player))
                    .Add(Restrictions.Eq("TeamId", teamId))
                    .List<Entities.Player>();
                return result;
            }
        }

        public IEnumerable<Entities.Player> GetAllPlayers()
        {
            return this.GetAll<Entities.Player>();
        }

        #endregion
    }
}
